import React, { Component } from 'react'
import { Row, Col, Form, Input, Modal, Switch, TreeSelect, Select, Tooltip, Icon } from 'antd'
import { PasswordInput } from 'antd-password-input-strength'
import md5 from 'md5'
import settings from '@/../config/defaultSettings'

const FormItem = Form.Item
// const Area = Input.TextArea
const { TreeNode } = TreeSelect
const { Option } = Select
@Form.create()
export default class AOEForm extends Component {
  // 校验账号唯一性
  // eslint-disable-next-line consistent-return
  checkAccount = (rule, value, callback) => {
    const { getFieldValue } = this.props.form
    const account = getFieldValue('account')
    const { item } = this.props
    if (item && item.id && value === item.account) {
      return callback()
    }
    const data = { account }
    this.props
      .dispatch({
        type: 'account/checkUnique',
        payload: data,
      })
      .then(r => {
        if (r.success) {
          return callback()
        }
        return callback('该账号已存在')
      })
  }

  // 关闭窗口
  handleCloseForm = () => {
    this.props.dispatch({
      type: 'account/updateState',
      payload: {
        modalType: '',
      },
    })
  }

  // 保存
  handleSaveClick = () => {
    const { dispatch, item } = this.props
    const { getFieldsValue, validateFields } = this.props.form
    validateFields(errors => {
      if (errors) {
        return
      }
      const data = {
        ...getFieldsValue(),
        id: item.id,
        userEntity: {},
      }
      // 加密密码
      if (data.password) {
        data.userEntity.password = md5(data.password)
        delete data.password
      }
      // 角色
      if (data.rolesId) {
        data.userEntity.roles = [{ id: data.rolesId }]
        delete data.rolesId
      }
      // userEntity的id
      if (item.userEntity && item.userEntity.id) {
        data.userEntity.id = item.userEntity.id
      }

      data.leader = data.leader ? '1' : '0'
      dispatch({
        type: 'account/save',
        payload: data,
      })
    })
  }

  // 渲染树节点
  renderTreeNodes = data =>
    data
      .map(item => {
        if (item.status === '0001') {
          if (item.children) {
            return (
              <TreeNode
                title={item.name}
                pathname={item.pathname ? item.pathname : item.name}
                key={item.id}
                value={item.pid}
              >
                {this.renderTreeNodes(item.children)}
              </TreeNode>
            )
          }
          return (
            <TreeNode
              title={item.name}
              pathname={item.pathname ? item.pathname : item.name}
              key={item.id}
              value={item.pid}
            />
          )
        }
        return null
      })
      .filter(item => item || false)

  renderRoleOptions = data =>
    data.map(item => (
      <Option key={item.id} value={item.id}>
        {item.name}
      </Option>
    ))

  // 渲染界面
  render() {
    const { getFieldDecorator } = this.props.form
    const { modalType, item, depData, submitting, roleData } = this.props
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
    }
    const formRowOne = {
      labelCol: { span: 4 },
      wrapperCol: { span: 19 },
    }
    return (
      <Modal
        maskClosable={false}
        confirmLoading={submitting}
        cancelText="取消"
        okText="提交"
        onCancel={() => this.handleCloseForm()}
        visible={modalType !== ''}
        width={660}
        onOk={() => this.handleSaveClick()}
        title={
          modalType === 'create'
            ? '新增用户信息'
            : modalType === 'edit'
            ? '编辑用户信息'
            : '查看用户信息'
        }
      >
        <Form>
          {/* 第一行 */}
          <Row>
            <Col span={12}>
              <FormItem label="手机号码" hasFeedback {...formItemLayout}>
                {getFieldDecorator('mobile', {
                  initialValue: item.mobile,
                  rules: [
                    { required: true, message: '请输入手机号' },
                    { pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: '请输入正确的手机号' },
                  ],
                })(
                  <Input
                    type="tel"
                    style={{ width: '100%' }}
                    maxLength={settings.inputMaxLength}
                  />,
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label="姓名" hasFeedback {...formItemLayout}>
                {getFieldDecorator('realityName', {
                  initialValue: item.realityName,
                  rules: [{ required: true, message: '请输入用户姓名' }],
                })(<Input maxLength={settings.inputMaxLength} />)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                label={
                  <span>
                    密码&nbsp;
                    <Tooltip title="密码应为 8-12 位的数字字母组合(不含空格)">
                      <Icon type="question-circle-o" />
                    </Tooltip>
                  </span>
                }
              >
                {getFieldDecorator('password', {
                  rules: [
                    {
                      required: modalType === 'create',
                      whitespace: true,
                      pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/,
                      message: '请输入8-16位包含数字及字母的密码',
                    },
                  ],
                })(
                  <PasswordInput autoComplete="new-password" maxLength={settings.inputMaxLength} />,
                )}
              </FormItem>
            </Col>
          </Row>
          {/* 第二行 */}
          <FormItem label="角色" hasFeedback {...formRowOne}>
            {getFieldDecorator('rolesId', {
              initialValue: item.userEntity ? item.userEntity.roles[0].id : null,
              rules: [{ required: true, message: '请选择用户角色' }],
            })(<Select placeholder="请选择用户角色">{this.renderRoleOptions(roleData)}</Select>)}
          </FormItem>
          <FormItem label="所属部门" hasFeedback {...formRowOne}>
            {getFieldDecorator('wxpartId', {
              initialValue: item.wxpartId,
              rules: [{ required: true, message: '请选择用户所属部门' }],
            })(
              <TreeSelect
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                showCheckedStrategy={TreeSelect.SHOW_ALL}
                allowClear
                showSearch
                treeNodeFilterProp="title"
                treeNodeLabelProp="pathname"
                placeholder="请选择所属部门节点"
              >
                {this.renderTreeNodes(depData)}
              </TreeSelect>,
            )}
          </FormItem>
          {/* 第三行 */}
          <Row>
            <Col span={12}>
              <FormItem label="邮箱" hasFeedback {...formItemLayout}>
                {getFieldDecorator('email', {
                  initialValue: item.email,
                  rules: [
                    {
                      type: 'email',
                      message: '请输入邮箱地址',
                    },
                  ],
                })(<Input autoComplete="off" maxLength={settings.inputMaxLength} />)}
              </FormItem>
            </Col>
          </Row>
          <FormItem label="是否是上级" {...formRowOne}>
            {getFieldDecorator('leader', {
              valuePropName: 'checked',
              initialValue: item.leader === '1',
            })(<Switch checkedChildren="是" unCheckedChildren="否" />)}
          </FormItem>
        </Form>
      </Modal>
    )
  }
}
